<?php


namespace App\Http\Controllers\Manage\Customer;


use App\Http\Controllers\Controller;
use App\Http\Requests\Manage\Customer\StoreRequest;
use App\Http\Requests\Manage\Customer\UpdateRequest;
use App\Http\Requests\Manage\Customer\AccountRequest;
use App\Http\Searchs\Manage\Customer\IndexSearch;
use App\Repositories\Customer;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    /**
     * @var Customer
     * @author luffyzhao@vip.126.com
     */
    private $customer;

    /**
     * IndexController constructor.
     * @param Customer $customer
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }

    /**
     * @param IndexSearch $search
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function index(IndexSearch $search)
    {
        return $this->response(
            $this->customer->paginate($search->toArray())
        );
    }

    /**
     * @param StoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function store(StoreRequest $request)
    {
        return $this->response(
            $this->customer->create($request->only([
                'name', 'remark', 'status'
            ]))
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function edit($id)
    {
        return $this->response(
            $this->customer->edit($id)
        );
    }

    /**
     * @param UpdateRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     * @author luffyzhao@vip.126.com
     */
    public function update(UpdateRequest $request, $id)
    {
        return $this->response(
            $this->customer->update($id, $request->only([
                'name', 'remark', 'status'
            ]))
        );
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function getAccount($id)
    {
        return $this->response(
            $this->customer->getAccount($id)
        );
    }

    /**
     * @param AccountRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @author luffyzhao@vip.126.com
     */
    public function account(AccountRequest $request, $id)
    {
        return $this->response(
            DB::transaction(function () use ($id, $request) {
                $this->customer->account($id, $request->only([
                    'name', 'remark', 'status', 'phone', 'email'
                ]));
            })
        );
    }
}
